package com.fowo.api.config;

import com.fowo.api.common.serializer.LongDeserializer;
import com.fowo.api.common.serializer.LongSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 配置 Jackson
 * @author yl_ls
 */
@Configuration
@Component
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class JacksonConfig implements WebMvcConfigurer {

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        // 添加长整型数据转换处理器，解决 js 中的 number 精度问题
        final LongSerializer longSerializer = new LongSerializer();
        final LongDeserializer longDeserializer = new LongDeserializer();

        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializerByType(Long.class, longSerializer)
                .serializerByType(Long.TYPE, longSerializer)
                .deserializerByType(Long.class, longDeserializer)
                .deserializerByType(Long.TYPE, longDeserializer);
        return new MappingJackson2HttpMessageConverter(builder.build());
    }
}
